﻿using System.Text.Json;
using System.Threading.Tasks;

namespace NiuX.EventBus
{
    /// <summary>
    ///    Event bus that uses JSON as the message format
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="NiuX.EventBus.IIntegrationEventHandler" />
    public abstract class JsonIntegrationEventHandler<T> : IIntegrationEventHandler
    {
        /// <summary>
        /// Handles the specified event name.
        /// </summary>
        /// <param name="eventName">Name of the event.</param>
        /// <param name="json">The json.</param>
        /// <returns></returns>
        public Task Handle(string eventName, string json)
        {
            T? eventData = JsonSerializer.Deserialize<T>(json);
            return HandleJson(eventName, eventData);
        }

        /// <summary>
        /// Handles the json.
        /// </summary>
        /// <param name="eventName">Name of the event.</param>
        /// <param name="eventData">The event data.</param>
        /// <returns></returns>
        public abstract Task HandleJson(string eventName, T? eventData);
    }
}
